/*******************用户信息数据操作***************************/
const util = require('../utils/util.js');
const cryptoJs = require("../utils/cryptoJs.js");
const defaultData = require("./defaultData.js");
const keyService = require('./keyService.js');

//获取OpenId
const getWxUserOpenID = (globalData) => {
  if (globalData.isLogin) {
    const userInfo = globalData.userInfo;
    return Promise.resolve({
      openID: userInfo.openID,
      appID: userInfo.appID,
      unionID: userInfo.unionID,
      cloudJsonName: globalData.cloudJsonName
    });
  }
  //重新获取
  return wx.cloud.callFunction({
    name: 'login',
    data: {},
  }).then(res => {
    const result = res.result;
    const nowTime = new Date().getTime();
    const userInfo = globalData.userInfo;

    userInfo.openID = result.openid;
    userInfo.unionID = result.unionid;
    userInfo.time = nowTime;

    globalData.isLogin = true;
    globalData.cloudJsonName = cryptoJs.MD5Encrypt(userInfo.openID).slice(4, 28);
    globalData.time = nowTime;

    util.setStorageData(globalData.localConfigName, globalData);

    return {
      openID: userInfo.openID,
      appID: userInfo.appID,
      unionID: userInfo.unionID,
      cloudJsonName: globalData.cloudJsonName
    }
  });
};

//获取是否授权用户信息
const getWxScopeUserInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: function(res) {
        if (!res.authSetting['scope.userInfo'])
          resolve(false);
        else
          resolve(true);
      },
      fail: function(err) {
        return reject(err);
      }
    })
  })
}
//获取用户公开信息
const getWxUserInfo = (globalData) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: function(res) {
        if (!res.authSetting['scope.userInfo'])
          resolve(undefined);

        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        wx.getUserInfo({
          success: function(userData) {
            const userInfo = globalData.userInfo;

            userInfo.nickName = userData.userInfo.nickName;
            userInfo.avatarUrl = userData.userInfo.avatarUrl;
            userInfo.gender = userData.userInfo.gender;
            userInfo.province = userData.userInfo.province;
            userInfo.city = userData.userInfo.city;
            userInfo.country = userData.userInfo.country;
            userInfo.language = userData.userInfo.language;
            userInfo.time = new Date().getTime();

            globalData.hasInfo = true;

            util.setStorageData(globalData.localConfigName, globalData);

            return resolve(userData.userInfo);
          },
          fail: function(err) {
            return reject(err);
          }
        })
      },
      fail: function(err) {
        return reject(err);
      }
    })
  })
};

const mergeCloudLocalData = (globalData, localJsonDataTime = undefined) => {
  return new Promise((resolve, reject) => {
    //加载云数据：开启了云存储，或者第一本地使用
    getWxUserOpenID(globalData).then(res => {
      const cloudJsonName = res.cloudJsonName;
      util.getCloudDbData(cloudJsonName).then(cloudData => {
        let isDemoData = true;
        let hasRetJsonData = false;
        let retJsonData = {};
        if (cloudData != undefined && cloudData != '') { //有云数据
          isDemoData = false;
          //本地没有数据、云数据大于本地数据时间
          if (localJsonDataTime == undefined || cloudData.time > localJsonDataTime) {
            hasRetJsonData = true;

            retJsonData.version = cloudData.version;
            retJsonData.time = cloudData.time;
            retJsonData.userInfo = cloudData.userInfo;
            retJsonData.category = cloudData.category;
            retJsonData.key = cloudData.key;
            retJsonData.version = cloudData.version;

            if (globalData.userInfo.enPassword != cloudData.userInfo.enPassword) { //云端修改了密码
              globalData.userInfo.enPassword = cloudData.userInfo.enPassword;
              globalData.authenPassword = '';
            }
          }
        } else { //没有云数据，初始化本地数据
          if (localJsonDataTime == undefined) { //本地没有数据
            isDemoData = true;
            hasRetJsonData = true;
            retJsonData = defaultData.getDefaultJsonData();

            const defaultPwd = '123456';
            retJsonData.userInfo.enPassword = cryptoJs.MD5Encrypt(defaultPwd);
            retJsonData = keyService.enJsonData(retJsonData, defaultPwd); //加密
          }
        }
        resolve({
          isDemoData: isDemoData,
          hasRetJsonData: hasRetJsonData,
          retJsonData: retJsonData
        })
      })
    }).catch(err => {
      reject(err);
    })
  });


}

//暴露接口
module.exports = {
  getWxUserOpenID: getWxUserOpenID,
  getWxScopeUserInfo: getWxScopeUserInfo,
  getWxUserInfo: getWxUserInfo,
  mergeCloudLocalData: mergeCloudLocalData
};